﻿using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using System.Collections;

public class Analog : Touchable {
    public static List<Analog> Analogs = new List<Analog>(); 

    public GameObject Knob;
    public Vector2 Current;

    private Camera oCamera;
    void Awake() {
        Analogs.Add(this);
    }
    // Use this for initialization
	void Start () {
		Knob.SetActive(false);
	    oCamera = Camera.allCameras.First(c => c != Camera.main);
	}

    void Update() {
        oCamera.enabled = false;
    }

	override public void TouchUpdate(Touch touch) {
        var c = oCamera.ScreenToWorldPoint(touch.position);
		Knob.SetActive(true);
		var p = transform.position;
		var r = transform.lossyScale.x/2 + Knob.transform.lossyScale.x/2;

		var nc = c - p;

		var length = Mathf.Sqrt(nc.x * nc.x + nc.y * nc.y);
		var factor = length > r ? r / length : 1;

		var force = new Vector2(nc.x * factor , nc.y * factor);
		Knob.transform.position = new Vector2(force.x + p.x, force.y + p.y);
		Current = new Vector2(force.x / r, force.y / r);

		Debug.DrawLine(Knob.transform.position, transform.position, Color.blue);
	}

	override public void TouchEnd(Touch touch) {
		Knob.SetActive (false);
		Current = new Vector2(0, 0);
	}
}
